package com.daocao.hua.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Parcelable;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.allen.library.SuperButton;
import com.daocao.hua.R;
import com.daocao.hua.api.Api;
import com.daocao.hua.api.bean.LiMuKeyBean;
import com.daocao.hua.api.bean.LiMuSignBean;
import com.daocao.hua.api.bean.LiMuTokenBean;
import com.daocao.hua.constant.Const;
import com.daocao.hua.constant.UserGlobal;
import com.daocao.hua.model.CertificationBasicsModel;
import com.daocao.hua.model.DealBeforeV3Model;
import com.daocao.hua.util.IdentityStepUtil;
import com.daocao.hua.util.Network;
import com.daocao.hua.util.PreferenceUtils;
import com.daocao.hua.util.RxLifeUtil;
import com.daocao.hua.util.ToastUtil;
import com.daocao.hua.view.Dialog;
import com.daocao.hua.view.FlowViewHorizontal;
import com.daocao.hua.view.V19FrameLayout;

import java.util.ArrayList;
import java.util.HashMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import kangcheng.com.lmzx_android_sdk_v10.bean.Fuction;
import kangcheng.com.lmzx_android_sdk_v10.bean.MessageEvent;
import kangcheng.com.lmzx_android_sdk_v10.bean.SignEvent;
import kangcheng.com.lmzx_android_sdk_v10.commom.sdk.LmzxSDK;
import kangcheng.com.lmzx_android_sdk_v10.commom.sdk.LmzxSdkImpl;
import kangcheng.com.lmzx_android_sdk_v10.util.callback.DataCallBack;
import kangcheng.com.lmzx_android_sdk_v10.util.callback.ObservableManager;

/**
 * Created by Administrator on 2018/6/10.
 */

public class V3YunYingIdentityActivity extends BaseActivity implements DataCallBack {
    @BindView(R.id.btn_back)
    ImageView btnBack;
    @BindView(R.id.txt_title)
    TextView txtTitle;
    @BindView(R.id.txt_right)
    TextView txtRight;
    @BindView(R.id.layout_title)
    V19FrameLayout layoutTitle;
    @BindView(R.id.step_view)
    FlowViewHorizontal stepView;
    @BindView(R.id.btn_submit)
    SuperButton btnSubmit;
    private Unbinder unbinder;
    public final static String SUCCESS = "0";
    public final static String LOGING_SUCCESS = "2";
    private String bizType = "mobile";
    private boolean initSuccess;
    private boolean isFail = false;
    private ArrayList<CertificationBasicsModel.DataBean> oneKeyData;
    private ArrayList<DealBeforeV3Model.DataBean.UplistsBean> SomeKeyData;

    private IdentityStepUtil stepUtil;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_yunying_identity_v3);
        initBar();
        unbinder = ButterKnife.bind(this);
        init();
    }

    private void init() {
        txtTitle.setText("运营商认证");
        oneKeyData = getIntent().getParcelableArrayListExtra(Const.KEY.ONE_KEY);

        SomeKeyData = getIntent().getParcelableArrayListExtra(Const.KEY.SOME_IDENTITY_KEY);
        stepUtil = new IdentityStepUtil(this);
        stepUtil.setIdentityData(bizType, txtTitle, stepView, oneKeyData, SomeKeyData);


        getKey(UserGlobal.getDealId());
    }

    private void showDialog() {
        Dialog.showV3DefaultDialog(this, "提示", "认证还未完成\n您确定要退出吗？", "取消", "确定", new Dialog.DialogDefaultClickListener() {
            @Override
            public void confirm() {
                finish();
            }

            @Override
            public void cancel() {

            }
        });
    }

    @Override
    public void onBackPressed() {
        showDialog();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        LmzxSdkImpl.getInstance().unRegistEvet();
        stepUtil = null;
        unbinder.unbind();
        unbinder = null;
    }


    @OnClick({R.id.btn_back, R.id.btn_submit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_back:
                showDialog();
                break;
            case R.id.btn_submit:
                if (!initSuccess) {
                    getKey(UserGlobal.getDealId());
                    return;
                }
                if (TextUtils.isEmpty(PreferenceUtils.getString(this, "mobile", "")) || Const.IS_DEBUG) {
                    LmzxSdkImpl.getInstance().initOperatorPreNo(this, "", true);
                } else {
                    LmzxSdkImpl.getInstance().initOperatorPreNo(this, PreferenceUtils.getString(this, "mobile", ""), false);
                }
                LmzxSdkImpl.getInstance().start(this, Fuction.LMZXSDKFunctionMobileCarrie, 0 + "", Const.LIMU_CALLBACK);
                break;
        }
    }

    public void getKey(String deal_id) {
        if (!Network.checkNetwork(this)) {
            ToastUtil.makeText(this, "网络连接失败").show();
            return;
        }
        loadingDialog.show();
        LiMuKeyBean bean = new LiMuKeyBean();
        bean.deal_id = deal_id;
        Api.api_service.getLiMuKey(bean).compose(RxLifeUtil.checkOn(this)).
                doFinally(() -> {
                    try {
                        loadingDialog.dismiss();
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {

                    //    初始化立木
                    Application.getInstance().LmsdkInit(result.getData().getKey(), result.getData().getUid());
                    LmzxSDK sdk = LmzxSdkImpl.getInstance();
                    sdk.registEvent(this);
                    sdk.setTextStyle(this, 0xFF4a4a4a);
                    sdk.setButtonStyle(this, 0xFF4C81FF);
                    sdk.setPageBack(this, 0xFFf4f4f4);
                    sdk.setBannerTextColor(this, 0xFFFFFFFF);
                    initSuccess = true;
                });
    }

    public void getSign(String params) {
        if (!Network.checkNetwork(this)) {
            ToastUtil.makeText(this, "网络连接失败").show();
            return;
        }

        LiMuSignBean bean = new LiMuSignBean();
        bean.params = params;
        Api.api_service.getSign(bean).compose(RxLifeUtil.checkOn(this)).
                doFinally(() -> {
                    try {

                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    HashMap<String, Object> hashMap = new HashMap<>();
                    hashMap.put("sign", result.getSign());
                    //Log.i("signString", "加签结果" + secondSign);
                    ObservableManager.getInstance().doLogic("sign", hashMap); //加签结果传给sdk。key值必须是"sign"。
                });
    }


    public void uploadToken(String deal_id, String token, String biztype) {
        if (!Network.checkNetwork(this)) {
            ToastUtil.makeText(this, "网络连接失败").show();
            return;
        }

        LiMuTokenBean bean = new LiMuTokenBean();
        bean.deal_id = deal_id;
        bean.token = token;
        bean.biztype = biztype;
        Api.api_service.uploadToken(bean).compose(RxLifeUtil.checkOn(this)).
                doFinally(() -> {
                    try {

                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    if (result.getStatus() == 1 && !isFail) {
                        ToastUtil.makeText(getApplicationContext(), "认证成功", Toast.LENGTH_SHORT).show();
                        stepUtil.goToNext();
                    }
                });
    }

    @Override
    public void signData(SignEvent signEvent) {
        String sign = signEvent.getSignStr();//r3qUEj6PhkTz8odjHC0OYTXbtlSxqWyQ  //1.收到sdk传来的字符串
        getSign(sign);
    }

    @Override
    public void messageData(MessageEvent event) {
        MessageEvent test = (MessageEvent) event;
//            Log.i("dasdadsadsadsasa", "code" + test.getCode() + ",message" + test.getMessage() + ",token" + test.getToken() + ",function" + test.getFunction() + ",hasmap" + test.getHashMap().toString());

        if (SUCCESS.equals(((MessageEvent) event).getCode())) {
            //具体哪个业务,参看文档的相关业务类型做处理
            int function = ((MessageEvent) event).getFunction();
            //服务密码
            if (function == Fuction.LMZXSDKFunctionMobileCarrie) {
                //...

            }
            //登录成功处理
        } else if (LOGING_SUCCESS.equals(((MessageEvent) event).getCode())) {
            //可以获取token值,记录提交请求,或者忽略掉
            isFail = false;
            uploadToken("", ((MessageEvent) event).getToken(), bizType);
            //查询失败
        } else {
            //失败处理,可忽略
//            Log.i("dadasdda", "失败code：" + ((MessageEvent) event).getCode() + "\ntoken=" + ((MessageEvent) event).getToken());
//            Intent intent = new Intent(this, MyIdentityActivity.class);
//            startActivity(intent);
            isFail = true;
            uploadToken("", ((MessageEvent) event).getToken(), bizType);
        }
    }
}
